package com.springapp.mvc.dm;

import com.google.common.collect.Lists;

import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Created by shangdong on 17/4/11.
 */
public class NewCountListenerImpl implements NewCountListener {

//    private List<DmConnClient> dmConnClientList;

    private ConcurrentHashMap<String,DmConnClient>  dmConnClientConcurrentHashMap = new ConcurrentHashMap<>();

//    private ConcurrentHashMap<String,DmConnClient>  dmConnClientConcurrentHashMap = new ConcurrentHashMap<>();

    public static ExecutorService executorService = Executors.newCachedThreadPool();

    public static ScheduledExecutorService timeLoginService = Executors.newScheduledThreadPool(10);

    public NewCountListenerImpl(List<User> userList) {
        loginAllUser(userList);
        timeLoginService.scheduleAtFixedRate(()->{
            for (Map.Entry<String, DmConnClient> entry : dmConnClientConcurrentHashMap.entrySet()) {
                DmConnClient client = entry.getValue();
                for (User user : userList) {
                    if (entry.getKey().equals(user.getUsername())){
                        executorService.execute(()->{
                            client.login(user.getUsername(),user.getPassword());
                        });
                        break;
                    }
                }
            }
        },20,20, TimeUnit.MINUTES);
        timeLoginService.scheduleAtFixedRate(()->{
            for (Map.Entry<String, DmConnClient> entry : dmConnClientConcurrentHashMap.entrySet()) {
                executorService.execute(()->{
                    DmConnClient client = entry.getValue();
                    int cartCount = client.getCartCount();
                    if (cartCount > 0){
                        client.pay(client.getUser().getUsername());
                    }
                });
            }
        },30,30,TimeUnit.SECONDS);
    }

    private void loginAllUser(List<User> userList) {
        List<Future<Boolean>> futures = Lists.newArrayList();
        for (User user : userList) {
            Future<Boolean> submit = executorService.submit(() -> {
                DmConnClient client = new DmConnClient();
                client.setUser(user);
                client.login(user.getUsername(), user.getPassword());
                dmConnClientConcurrentHashMap.put(user.getUsername(), client);
                return true;
            });
            futures.add(submit);
        }
//        boolean finalLogin =
        for (Future<Boolean> future : futures) {
            try {
                if (future.get()){
                    return;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void hasCount(String count, Product product) {
        for (Map.Entry<String, DmConnClient> stringDmConnClientEntry : dmConnClientConcurrentHashMap.entrySet()) {
            executorService.execute(()->{
                String user = stringDmConnClientEntry.getKey();
                DmConnClient client = stringDmConnClientEntry.getValue();
                if (client.isLogged()){
                    client.addCartAndPay(count,product,user);
                }else{
                    System.out.println("没有登录无法加入购物车下单 ！账号 = "+ client.getUser().getUsername());
                    client.login(client.getUser().getUsername(),client.getUser().getPassword());
                    client.addCartAndPay(count,product,user);
                }
            });
        }

    }
}
